all files / src/validators/ bid.validator.ts

78.38% Statements 29/37
62.5% Branches 15/24
100% Functions 2/2
80.56% Lines 29/36
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66                                                                          
import { Game, PlayersBid, Phase } from '../game.interfaces';
import { Bid } from '../game.actions';
import { getNextTurn } from '../helpers/players.helpers';
import { hasMarriage } from '../helpers/cards.helpers';
import * as _ from 'lodash';
import { hasPlayerAlreadyPassed, isMaxBid, hasTwoPasses, getHighestBid, isAchievableBid, isValidBidValue } from '../helpers/bid.helpers';
 
export function canBid(state: Game, action: Bid): boolean {
    Iif (state.phase !== Phase.BIDDING_IN_PROGRESS) {
        return false;
    }
 
    Iif(isBiddingFinished(state)) {
        return false
    }
 
    Iif (!isAchievableBid(action)) {
        return false;
    }
 
    Iif (!isValidBidValue(action)) {
        return false;
    }
 
    const lastBiddingPlayerId = state.bid[0].player;
    const nextAllowedPlayerToBid = getNextTurn(state.players, lastBiddingPlayerId);
    if (action.player !== nextAllowedPlayerToBid) {
        return false;
    }
 
    if (action.pass) {
        Iif(hasPlayerAlreadyPassed(state.bid, action.player)) {
            return false;
        } else {
            return true;
        }
    }
 
    const lastBidValue = getHighestBid(state.bid);
    Iif (action.bid <= lastBidValue.bid) {
        return false;
    }
 
    const playerId = action.player;
    const playerCards = state.cards[playerId];
    const hasPlayerMarriage = hasMarriage(playerCards);
 
    Iif (action.bid >= 130 && !hasPlayerMarriage) {
        return false;
    }
    return true;
};
 
export function isBiddingFinished(state: Game): boolean {
    Iif (state.bid.length === 0) return false;
 
    const isMax = _.chain(state.bid)
        .head()
        .thru(isMaxBid)
        .value();
 
    const hasTwoPlayerPasses = hasTwoPasses(state.bid);
 
    return hasTwoPlayerPasses || isMax;
}